package com.taiji.workOrder.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.taiji.common.core.domain.entity.SysUser;
import com.taiji.common.utils.DateUtils;
import com.taiji.common.utils.SecurityUtils;
import com.taiji.common.utils.uuid.IdUtils;
import com.taiji.system.mapper.SysUserMapper;
import com.taiji.system.service.impl.SysDictDataServiceImpl;
import com.taiji.workOrder.Utils.Const;
import com.taiji.workOrder.domain.*;
import com.taiji.workOrder.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taiji.workOrder.service.IMyOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 我的工单Service业务层处理
 *
 * @author taiji
 * @date 2023-03-04
 */
@Service
public class MyOrderServiceImpl implements IMyOrderService
{
    @Autowired
    private MyOrderMapper myOrderMapper;

    private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private SysDictDataServiceImpl dictDataService;

    @Autowired
    private OrderEnclosureMapper enclosureMapper;


    @Autowired
    private OrderLogsMapper orderLogsMapper;

    @Autowired
    private UserProjectMapper userProjectMapper;

    @Autowired
    private SysUserMapper sysUserMapper;



    /**
     * 查询我的工单
     *
     * @param id 我的工单主键
     * @return 我的工单
     */
    @Override
    public WorkOrder selectMyOrderById(String id)
    {

        return myOrderMapper.selectMyOrderById(id);
    }

    @Override
    public WorkOrder getDetail(String id)
    {
        // 根据id拿到工单
        WorkOrder workOrder = myOrderMapper.selectMyOrderById(id);
        OrderEnclosure orderEnclosure = new OrderEnclosure();
        // 新建工单附件对象 设置对象的 工单编号
        orderEnclosure.setWorkNumber(workOrder.getWorkNumber());
        List<OrderEnclosure> orderEnclosures = enclosureMapper.selectOrderEnclosureList(orderEnclosure);
        // 获取工单附件List
        workOrder.setOrderEnclosureList(orderEnclosures);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        //获取流转日志 根据处理时间先后排序 返回前端
        List<OrderLogs> orderLogsList = orderLogsMapper.selectOrderLogsList(orderLogs);
        System.out.println(orderLogsList);

        workOrder.setOrderLogs(orderLogsList);
        return workOrder;
    }

    @Override
    public List<SysUser> getDealPerson(String projectCode){
        List<UserProject> userProjects = userProjectMapper.selectUserProjectByProjectCode(projectCode);
        List<Long> collect = userProjects.stream()
                .map(s -> s.getUserId())
                .collect(Collectors.toList());
        if (collect.size()>0){
            return sysUserMapper.selectProjectUserByIds(collect);
        }
        else {
            return new ArrayList<SysUser>();
        }
    }

    /**
     * 查询我的工单列表
     *
     * @param myOrder 我的工单
     * @return 我的工单
     */
    @Override
    public List<WorkOrder> selectMyOrderList(WorkOrder workOrder)
    {
        workOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        return myOrderMapper.selectMyOrderList(workOrder);
    }

    /**
     * 新增我的工单
     *
     * @param myOrder 我的工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMyOrder(WorkOrder workOrder) throws Exception {
        System.out.println(workOrder);
        workOrder.setId(IdUtils.fastSimpleUUID());
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = new Date();
        String format = sdf.format(date);
        //todo 这里现在用的是工单获取项目code拼接的，后期可以考虑改成从字典中获取当前项目，isBmgz=0的
//        String bmgz = workOrder.getProjectCode().concat("_").concat("bmgz");
//        String s = dictDataService.selectDictValue(workOrder.getProjectCode(), bmgz, "工单");
//        if (null==s){
//            throw new Exception("该项目尚未配置工单编码规则，请先配置编码规则后再新增工单");
//        }
        //根据当前项目代码 获取项目信息
        Project project = projectMapper.selectProjectByCode(workOrder.getProjectCode());
        //工单编码  随机生成4位字符
        String rand =workOrder.getWorkNumber().substring(workOrder.getWorkNumber().length()-4,workOrder.getWorkNumber().length());
//        String rand = ChineseTextToPinyin.ramdomNumber();
        //todo 工单编码回头我就直接删除了，由前端传给后台
//        String number = workOrder.getProjectCode().concat("-")
//                .concat(s).concat("-").concat(format)
//                .concat("-").concat(rand);
//        workOrder.setWorkNumber(number);
        workOrder.setRand(rand);
        workOrder.setCreateTime(DateUtils.getNowDate());
        workOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        workOrder.setStatus(workOrder.getStatus());
        String key = Const.WorkOrderStatus.DELAYED.getKey();
        //此处为工单文件
        if (workOrder.getOrderEnclosureList()!=null){
            for (int i = 0; i <workOrder.getOrderEnclosureList().size() ; i++) {
                OrderEnclosure orderEnclosure = workOrder.getOrderEnclosureList().get(i);
                orderEnclosure.setEnclosureCode(orderEnclosure.getUrl().substring(orderEnclosure.getUrl().lastIndexOf("/")+1,orderEnclosure.getUrl().length()));
                orderEnclosure.setWorkNumber(workOrder.getWorkNumber());
                orderEnclosure.setCreateBy(nickName);
                orderEnclosure.setCreateTime(date);
                enclosureMapper.insertOrderEnclosure(orderEnclosure);
            }
        }
        //工单日志
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents("工单创建");
        if (workOrder.getDealLog()!=null){
            orderLogs.setRemark(workOrder.getDealLog());
        }
        orderLogsMapper.insertOrderLogs(orderLogs);
        return myOrderMapper.insertMyOrder(workOrder);
    }

    /**
     * 修改我的工单
     *
     * @param myOrder 我的工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMyOrder(WorkOrder workOrder)
    {
        workOrder.setUpdateTime(DateUtils.getNowDate());
        //项目日志
        OrderLogs orderLogs = new OrderLogs();
        String workNumber = workOrder.getWorkNumber();
        orderLogs.setWorkNumber(workNumber);
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = new Date();
        orderLogs.setCreateTime(date);
        orderLogs.setCreateBy(nickName);
        orderLogs.setContents("工单修改");
        if (workOrder.getDealLog()!=null){
            orderLogs.setRemark(workOrder.getDealLog());
        }
        //项目文件
        enclosureMapper.deleteOrderEnclosureByWorkNumber(workNumber);
        if (workOrder.getOrderEnclosureList()!=null){
            for (int i = 0; i <workOrder.getOrderEnclosureList().size(); i++) {
                OrderEnclosure orderEnclosure = workOrder.getOrderEnclosureList().get(i);
                orderEnclosure.setEnclosureCode(orderEnclosure.getUrl().substring(orderEnclosure.getUrl().lastIndexOf("/")+1,orderEnclosure.getUrl().length()));
                orderEnclosure.setWorkNumber(workNumber);
                orderEnclosure.setCreateBy(nickName);
                orderEnclosure.setCreateTime(date);
                enclosureMapper.insertOrderEnclosure(orderEnclosure);
            }
        }
        return myOrderMapper.updateMyOrder(workOrder);
    }

    /**
     * 批量删除我的工单
     *
     * @param ids 需要删除的我的工单主键
     * @return 结果
     */
    @Override
    public int deleteMyOrderByIds(String[] ids)
    {
        return myOrderMapper.deleteMyOrderByIds(ids);
    }

    /**
     * 删除我的工单信息
     *
     * @param id 我的工单主键
     * @return 结果
     */
    @Override
    public int deleteMyOrderById(String id)
    {
        return myOrderMapper.deleteMyOrderById(id);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int revert(WorkOrder workOrder)
    {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        String dealPerson = workOrder.getDealPerson();
        SysUser sysUser = sysUserMapper.selectUserByUserName(dealPerson);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"转单给"+sysUser.getNickName());
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogs.setRemark(workOrder.getRemark());
        orderLogsMapper.insertOrderLogs(orderLogs);
        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setRemark(null);
        return myOrderMapper.updateMyOrder(workOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int finish(String workNumber)
    {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        WorkOrder workOrder = myOrderMapper.selectMyOrderByWorkNumber(workNumber);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"完成工单");
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogsMapper.insertOrderLogs(orderLogs);
        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setStatus(Const.WorkOrderStatus.FINISH.getKey());
        workOrder.setRemark(null);




        return myOrderMapper.updateMyOrder(workOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int close(String workNumber,String remark)
    {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        WorkOrder workOrder = myOrderMapper.selectMyOrderByWorkNumber(workNumber);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"关闭工单");
        orderLogs.setRemark(remark);
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogsMapper.insertOrderLogs(orderLogs);
        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setStatus(Const.WorkOrderStatus.CLOSED.getKey());


        return myOrderMapper.updateMyOrder(workOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int disallowed(String workNumber,String remark)
    {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        WorkOrder workOrder = myOrderMapper.selectMyOrderByWorkNumber(workNumber);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"驳回工单");
        orderLogs.setRemark(remark);
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogsMapper.insertOrderLogs(orderLogs);
        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setStatus(Const.WorkOrderStatus.DOING.getKey());

        return myOrderMapper.updateMyOrder(workOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int accept(String workNumber)
    {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        WorkOrder workOrder = myOrderMapper.selectMyOrderByWorkNumber(workNumber);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"开始受理工单");
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogsMapper.insertOrderLogs(orderLogs);
        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setDealPerson(SecurityUtils.getLoginUser().getUser().getUserName());
        workOrder.setStatus(Const.WorkOrderStatus.DOING.getKey());
        //workOrder.setRemark(null);
        return myOrderMapper.updateMyOrder(workOrder);
    }

    @Override
    public WorkOrder selectWorkOrderByWorkNumber(String workNumber) {

        return myOrderMapper.selectWorkOrderByWorkNumber(workNumber);
    }

    @Override
    public int submit(String workNumber) {
        Date date = new Date();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        //日志
        WorkOrder workOrder = myOrderMapper.selectMyOrderByWorkNumber(workNumber);
        OrderLogs orderLogs = new OrderLogs();
        orderLogs.setCreateBy(nickName);
        orderLogs.setCreateTime(date);
        orderLogs.setContents(nickName+"提交工单");
        orderLogs.setWorkNumber(workOrder.getWorkNumber());
        orderLogsMapper.insertOrderLogs(orderLogs);

        workOrder.setUpdateTime(date);
        workOrder.setUpdateBy(nickName);
        workOrder.setStatus(Const.WorkOrderStatus.WAITHANDLE.getKey());
        //workOrder.setRemark(null);

        return myOrderMapper.updateMyOrder(workOrder);
    }
}
